GApp.Attributes = {
    list: [],
    url: '/?url=configAttributes/attributes'
};

(function (P) {
    P.getAttribute = function (id) {
        var attr = null;
        $.each(P.list, function (i, v) {
           if (v.id === id) {
               attr = P.list[i];
           } 
        });
        return attr;
    },
    
    P.updateTable = function (url) {
         $.ajax ({
            type: 'get',
            url: GApp.baseURL + url
        })
        .done (function (data) {
            var tmp = [];
            var json = JSON.parse (data);
            
            P.list.length = 0;
            
            $('#dataTables-attributes > tbody').html ('');
            $.each(json, function (i, v) {
                tmp.push ('<tr class="odd gradeX">');
                tmp.push ('<td align="center">');
                tmp.push ('<a href="#" onclick="GApp.Attributes.modifyAttribute (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-pencil-square fa-lg"></i></a> '); 
                tmp.push ('<a href="#" onclick="GApp.Attributes.removeAttribute (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-minus-square fa-lg"></i></a>');
                tmp.push ('</td>');
                tmp.push ('<td>' + v.name + '</td>');
                tmp.push ('<td>' + v.type + '</td>');
                tmp.push ('<td>' + v.defaultValue + '</td>');
                tmp.push ('</tr>');
                P.list.push (v);
            });
            
            $('#dataTables-attributes > tbody').html (tmp.join (''));
        })
        .fail (function () {
            console.log ('ERROR: updateTable');
        });
    },
    
    P.sendAttribute = function (data, okCallback, errorCallback) {
        var url = ($('#attributeIdForm').val () !== '') ? 'modifyAttribute' : 'addAttribute';
        
        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configAttributes/' + url,
            data: {
                id: data.id,
                name: data.name,
                type: data.type,
                defaultValue: data.defaultValue
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.sendRemoveAttribute = function (data, okCallback, errorCallback) {        
        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configAttributes/removeAttribute',
            data: {
                id: data.id
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.validateAndCommitModal = function () {
        var errors = 0;
        var attribute = {
            id: $('#attributeIdForm').val () || null,
            name: $('#attributeNameForm').val () || null,
            type: $('#attributeTypeForm').val (),
            defaultValue: $('#attributeDefaultValueForm').val ()
        };

        if (!attribute.name || attribute.name.length == 0) {
            $('#attributeNameForm').parent ().addClass ('has-error');
            errors++;
        }
        else {
            $('#attributeNameForm').parent ().removeClass ('has-error');
        }

        if (errors === 0) {
             P.sendAttribute (attribute, 
                 function () {
                    // OK
                    $('#attributeModalDlg').modal ('hide');
                    P.updateTable (GApp.Attributes.url);
                 },
                 function () {
                    // Error
                    console.log  ('Error: validateAndCommitModal');
                 }
             );
        }
    },
    
    P.confirmFormAttribute = function (attribute) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>¿Quieres eliminar el atributo seleccionado?</label>');
        form.push ('</div>');
        
        $('#attributeModalLabel').text ('Eliminar atributo');
        $('#attributeAcceptModalDlg').on ('click', function () {
           P.sendRemoveAttribute (attribute, 
                 function () {
                    // OK
                    $('#attributeModalDlg').modal ('hide');
                    P.updateTable (GApp.Attributes.url);
                 },
                 function () {
                    // Error
                    console.log  ('Error: confirmFormAttribute');
                 }
            );
        });
        
        $('#attributeModalBody').html (form.join (''));
        $('#attributeModalDlg').modal ();
        $('#attributeModalDlg').on ('hidden.bs.modal', function () {
            $('#attributeAcceptModalDlg').off ('click');
            $('#attributeModalDlg').off ('hidden.bs.modal');
        });
        
        if (attribute) {
            $('#attributeIdForm').val (attribute.id);
        }
        
        return false;
    },
    
    P.showFormAttribute = function (title, attribute) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>Nombre</label>');
        form.push ('<input class="form-control" placeholder="Nombre del atributo" id="attributeNameForm">');
        form.push ('</div>');
        form.push ('<div class="form-group">');
        form.push ('<label>Tipo</label>');
        form.push ('<select class="form-control" id="attributeTypeForm">');
        form.push ('<option value="STRING">Cadena</option>');
        form.push ('<option value="NUMERIC">Número</option>');
        form.push ('<option value="DATE">Fecha</option>');
        form.push ('</select>');
        form.push ('</div>');
        form.push ('<div class="form-group">');
        form.push ('<label>Valor predeterminado</label>');
        form.push ('<input class="form-control" placeholder="Nombre del atributo" id="attributeDefaultValueForm">');
        form.push ('<input type="hidden" id="attributeIdForm">');
        form.push ('</div>');
        
        $('#attributeModalLabel').text (title);
        $('#attributeAcceptModalDlg').on ('click', function () {
           P.validateAndCommitModal ();
        });
        
        $('#attributeModalBody').html (form.join (''));
        $('#attributeModalDlg').modal ();
        $('#attributeModalDlg').on ('hidden.bs.modal', function () {
            $('#attributeAcceptModalDlg').off ('click');
            $('#attributeModalDlg').off ('hidden.bs.modal');
        });
        
        if (attribute) {
            $('#attributeNameForm').val (attribute.name);
            $('#attributeTypeForm').val (attribute.type);
            $('#attributeDefaultValueForm').val (attribute.defaultValue);
            $('#attributeIdForm').val (attribute.id);
        }
        
        return false;
    },

    P.newAttribute = function () {        
        return P.showFormAttribute ('Nuevo atributo');
    },

    P.modifyAttribute = function (attributeId) {
        return P.showFormAttribute ('Modificar atributo', P.getAttribute (attributeId));
    }
    
    P.removeAttribute = function (attributeId) {
        return P.confirmFormAttribute (P.getAttribute (attributeId));
    }
} (GApp.Attributes));

if (document.URL.indexOf ('url=configAttributes') > 0) {
    $(document).ready (function () {
        GApp.Attributes.updateTable (GApp.Attributes.url);
    });
}
